package cn.edu.hizee.gps.controller;

import cn.edu.hizee.gps.dao.*;
import cn.edu.hizee.gps.model.*;
import cn.edu.hizee.gps.util.HttpRequest;
import cn.edu.hizee.gps.util.MulitUtil;
import cn.edu.hizee.gps.util.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * @author ZX
 */
@RequestMapping("user")
@RestController
public class UserController extends BaseController {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private UserDeviceRepository userDeviceRepository;

    @Autowired
    private ContactRepository contactRepository;

    @Autowired
    private SiteRepository siteRepository;

    @Autowired
    private UserInfoRepository userInfoRepository;

    @Autowired
    private Site2Repository site2Repository;

    @Autowired
    private TimeUtil timeUtil;

    @Autowired
    private RedisTemplate redisTemplate;

    private static String HELP_FLAG = "HELP";
    private static Integer second = 5;


    /**
     * 地图显示时个人信息
     * @param username
     * @param response
     * @return
     */
    @GetMapping("userInfo")
    public String userInfo(String username,HttpServletResponse response){
        User user = userRepository.findAllByRealName(username);
        List<Map> list = userInfoRepository.findUserInfo(user.getId());
        return ajaxReturn(response,0,"true",list);
    }


    /**
     * 地图显示时所对应联系人的信息
     * @param username
     * @param response
     * @return
     */
    @GetMapping("contactInfo")
    public String contactInfo(String username,HttpServletResponse response){
        User user = userRepository.findAllByRealName(username);
        List<Contact> list = contactRepository.findAllContact(user.getId());
        return ajaxReturn(response,0,"true",list);
    }


    /**
     * 用户登陆
     * @param phone
     * @param password
     * @param response
     * @return
     */
    @PostMapping(value = "login_user")
    public String loginUser(String phone, String password, HttpServletResponse response){
        User user = userRepository.findByPhoneAndPassword(phone, password);
        if(user != null){
            List<Map> list  = contactRepository.findContactList(user.getId());
            List<Map> list1 = userRepository.findUserList(user.getId());
            UserInfo userInfo = userInfoRepository.findByUserId(user.getId());
            return ajaxReturn(response,1,"success",list,user,list1,user.getId(),userInfo);
        }
        return ajaxReturn(response,0,"false",null);
    }


    /**
     * 接受经纬度
     * @param response
     * @param lng
     * @param lat
     * @param userId
     * @return
     */
    @PostMapping(value = "accept_position")
    public String acceptLngAndLat(HttpServletResponse response, String lng, String lat, String userId, String type) throws IOException {
        // type=1 分享 记最新经纬度 type=2 一串经纬度 type=3 紧急求助同类人
        System.out.println(userId);
        if(lng != null || lat != null || type != null) {
            if (type.equals("1")) {
                PushInfo pushInfo = (PushInfo) redisTemplate.opsForValue().get(userId + "type1");
                if (pushInfo == null) {
                    PushInfo pushInfo1 = new PushInfo();
                    pushInfo1.setUserId(userId);
                    pushInfo1.setLng(lng);
                    pushInfo1.setLat(lat);
                    redisTemplate.opsForValue().set(userId + "type1", pushInfo1);
                } else {
                    pushInfo.setLng(lng);
                    pushInfo.setLat(lat);
                    redisTemplate.opsForValue().set(userId + "type1", pushInfo);
                }
                redisTemplate.opsForValue().set(userId + "type2", null);
                return ajaxReturn(response, 1, "success", null);
            } else if (type.equals("2")) {
                redisTemplate.opsForValue().set(userId + "type1", null);
                userRepository.updateIsSafe(Integer.valueOf(userId));
                PositionInfo positionInfo = (PositionInfo) redisTemplate.opsForValue().get(userId + "type2");
                System.out.println(positionInfo);
                if (positionInfo != null) {
                    List list = new ArrayList();
                    list.add(userId);
                    positionInfo.setUserId(list);
                    positionInfo.getLng().add(lng);
                    positionInfo.getLat().add(lat);
                    redisTemplate.opsForValue().set(userId + "type2", positionInfo);
                    return ajaxReturn(response, 1, "success", null);
                } else {
                    /*
                     * 发送短信
                     * */
                    timeUtil.pushDX(userId);
                    PositionInfo positionInfo1 = new PositionInfo(lng, lat, userId);
                    redisTemplate.opsForValue().set(userId + "type2", positionInfo1);
                    return ajaxReturn(response, 1, "success", null);
                }
            } else if (type.equals("3")) {
                redisTemplate.opsForValue().set(userId + "type1", null);
                userRepository.updateIsSafe(Integer.valueOf(userId));
                PositionInfo positionInfo = (PositionInfo) redisTemplate.opsForValue().get(userId + "type2");
                if (positionInfo != null) {
                    List list = new ArrayList();
                    list.add(userId);
                    positionInfo.setUserId(list);
                    positionInfo.getLng().add(lng);
                    positionInfo.getLat().add(lat);
                    System.out.println("positionInfo " + positionInfo.toString());
                    redisTemplate.opsForValue().set(userId + "type2", positionInfo);
                } else {
                    /*
                     * 发送短信
                     * */
                    timeUtil.pushDX(userId);
                    PositionInfo positionInfo1 = new PositionInfo(lng, lat, userId);
                    redisTemplate.opsForValue().set(userId + "type2", positionInfo1);
                }

                Site site = new Site(Integer.valueOf(userId), lng, lat);
                if(siteRepository.countSitesByUserId(Integer.valueOf(userId)) == 0) {
                    siteRepository.save(site);
                }else {
                    siteRepository.updateSite(Integer.valueOf(userId), lng, lat);
                }
                return ajaxReturn(response, 1, "success", null);
            }
        }
        return ajaxReturn(response, 0, "false", null);

    }

    public String findDevNum(String userId){
        return userDeviceRepository.findDevNum(userId);
    }

    public Integer findUserId(String devNum){
        return userDeviceRepository.findUserId(devNum);
    }

    /**
     * 插入硬件数据
     * @param requestMsg
     * @return
     */
    @PostMapping("insert_dev_info")
    public String acceptDevNumInfo(HttpServletResponse response,String requestMsg) throws InterruptedException, IOException {
        MulitUtil mulitUtil = new MulitUtil();
        List list = new ArrayList();
        PushInfo pushInfo = new PushInfo();
        if(requestMsg.indexOf(HELP_FLAG) != -1){
            pushInfo = mulitUtil.analysis_help(requestMsg);
            String id = String.valueOf(findUserId(pushInfo.getDeviceNum()));
            PositionInfo positionInfo = (PositionInfo) redisTemplate.opsForValue().get(id + "type2");
            List list1 = new ArrayList();
            list1.add(id);
            if (positionInfo != null) {
                /*
                 * 发送短信
                 * */
//                timeUtil.pushDX(id);
                positionInfo.getLng().add("30.298995");
                positionInfo.getLat().add("119.831316");
                positionInfo.getLng().add("30.298995");
                positionInfo.getLat().add("119.831316");
                positionInfo.setUserId(list1);
                positionInfo.setExtra(pushInfo.getExtra());
                redisTemplate.opsForValue().set(id + "type2", positionInfo);
            } else {
                /*
                 * 发送短信
                 * */
                timeUtil.pushDX(id);
                positionInfo = new PositionInfo();
                positionInfo.getLng().add("30.298995");
                positionInfo.getLat().add("119.831316");
                positionInfo.getLng().add("30.298995");
                positionInfo.getLat().add("119.831316");
                positionInfo.setUserId(list1);
                positionInfo.setExtra(pushInfo.getExtra());
                redisTemplate.opsForValue().set(id + "type2", positionInfo);
                return ajaxReturn(response,2, "success", null);
            }
            timeUtil.Time(second,id,positionInfo);
            return ajaxReturn(response,2, "success", null);
        }else {
            pushInfo = mulitUtil.analysis(requestMsg);
            String id = String.valueOf(findUserId(pushInfo.getDeviceNum()));
            PositionInfo positionInfo = (PositionInfo) redisTemplate.opsForValue().get(id + "type2");
            JsonTf jsonTf = mulitUtil.gps_tf(pushInfo.getLng(), pushInfo.getLat());
            if (positionInfo != null) {
                /*
                 * 发送短信
                 * */
//                timeUtil.pushDX(id);
                positionInfo.getLng().add(jsonTf.getResult().get(0).getLng());
                positionInfo.getLat().add(jsonTf.getResult().get(0).getLat());
                positionInfo.getTime().add(pushInfo.getTime());
                list.add(id);
                positionInfo.setUserId(list);
                positionInfo.setExtra(pushInfo.getExtra());
                redisTemplate.opsForValue().set(id + "type2", positionInfo);
            } else {
                /*
                 * 发送短信
                 * */
                timeUtil.pushDX(id);
                positionInfo = new PositionInfo();
                positionInfo.getLng().add(jsonTf.getResult().get(0).getLng());
                positionInfo.getLat().add(jsonTf.getResult().get(0).getLat());
                positionInfo.getTime().add(pushInfo.getTime());
                list.add(id);
                positionInfo.setUserId(list);
                positionInfo.setExtra(pushInfo.getExtra());
                redisTemplate.opsForValue().set(id + "type2", positionInfo);
            }
            timeUtil.Time(second,id,positionInfo);
            return ajaxReturn(1, "success", null);
        }
    }

    @PostMapping("find_contact")
    public String findALLContactId(HttpServletResponse response, String userId){
        List<Integer> list = contactRepository.findALLContactId(userId);
        return ajaxReturn(response, 1,"success",list);
    }

    @PostMapping("find_user")
    public String findUser(HttpServletResponse response, Model model, Integer pn){
        List<User> list = userRepository.findAll();
        model.addAttribute("userList",list);
        return ajaxReturn(response,list);
    }


    /**
     * 接受有无联系人响应救援
     * @param userId
     * @return
     */
    @PostMapping("wait_flag")
    public String waitFlag(String userId){
        PositionInfo positionInfo = (PositionInfo) redisTemplate.opsForValue().get(userId + "type2");
        positionInfo.setFlag("1");
        redisTemplate.opsForValue().set(userId + "type2", positionInfo);
        return ajaxReturn(1, "success", null);
    }

    /**
     * 接受有无联系人响应救援
     * @param phone
     * @param password
     * @param yzm
     * @return
     */
    @PostMapping("register")
    public String register(String phone, String password, String yzm){
        String check_yzm = (String) redisTemplate.opsForValue().get("yzm"+yzm);
        if(check_yzm.equals(yzm)){
            User user = new User();
            user.setPhone(phone);
            user.setPassword(password);
            userRepository.save(user);
            redisTemplate.opsForValue().set("yzm"+yzm, null);
            return ajaxReturn(1, "success", null);
        }else {
            return ajaxReturn(1, "验证码错误", null);
        }
    }

    /**
     * 检查验证码
     * @param phone
     * @return
     */
    @GetMapping("check_yzm")
    public String checkYzm(String phone) throws IOException {
        System.out.println("aaa");
        String yzm = timeUtil.pushYZM(phone);
        redisTemplate.opsForValue().set("yzm"+yzm, yzm);
        return ajaxReturn(1, "success", null);
    }


    /**
     * 添加用户
     * @param response
     * @param model
     * @param phone
     * @param realName
     * @param nickname
     * @param password
     * @return
     */
    @PostMapping(value = "add_user")
    public String addUser(HttpServletResponse response, Model model, String phone, String realName, String nickname, String password){
        User user = new User();
        user.setPassword(password);
        user.setPhone(phone);
        user.setNickname(nickname);
        user.setRealName(realName);
        if(userRepository.findByPhoneAndPassword(phone, password) == null) {
            if (userRepository.save(user) != null) {
                return ajaxReturn(response, 0, "success", null);
            } else {
                return null;
            }
        }else {
            return ajaxReturn(response, 0, "此用户已存在", null);
        }
    }


    /**
     * 修改用户
     * @param response
     * @param phone
     * @param realName
     * @param nickname
     * @param password
     * @return
     */
    @RequestMapping(value = "edit_user")
    public String editUser(HttpServletResponse response, HttpServletRequest request, String phone, String realName, String nickname, String password){
        if(request.getMethod().equalsIgnoreCase("GET")){

        }
        User user = new User();
        user.setPassword(password);
        user.setPhone(phone);
        user.setNickname(nickname);
        user.setRealName(realName);
        if(userRepository.findByPhoneAndPassword(phone, password) == null) {
            if (userRepository.save(user) != null) {
                return ajaxReturn(response, 0, "success", null);
            } else {
                return null;
            }
        }else {
            return ajaxReturn(response, 0, "此用户已存在", null);
        }
    }



}
